<template>
	<WithFixedPageContainer v-model:page="page">
		<!-- 搜索表单 -->
		<div class="bg-white p-2 rounded-md">
			<BasicTableFrom :formList="formList" @search="handleSearch">
				<template #menu>
					<el-button type="primary" @click="handleAddNew">新增客户</el-button>
				</template>
			</BasicTableFrom>
		</div>
		<!-- 表格 -->
		<template #table>
			<div class="h-full overflow-auto">
				<BasicTable
					:data="tableData"
					:option="tableColumns"
					v-model:page="page"
					:table-loading="loading"
				>
					<template #orderCount="{ row }">
						<el-link type="primary" @click="handleOrderCount(row)">{{
							row.orderCount
						}}</el-link>
					</template>
					<template #status="{ row }">
						<span
							:style="{
								color:
									row.status === '正常'
										? 'var(--el-color-success)'
										: 'var(--el-color-danger)',
							}"
						>
							{{ row.status }}
						</span>
					</template>
					<template #menu="{ row }">
						<template v-if="row.status === '正常'">
							<el-button text type="primary" @click="handleEdit(row)"
								>编辑</el-button
							>
							<el-button text type="danger" @click="handleDisable(row)"
								>停用</el-button
							>
						</template>
						<template v-else>
							<el-button text type="success" @click="handleEnable(row)"
								>启用</el-button
							>
						</template>
						<el-button text type="primary" @click="handleAddressBook(row)"
							>地址薄</el-button
						>
					</template>
				</BasicTable>
			</div>
		</template>
		<AddCustomer ref="addCustomerRef" />
		<AddressBook ref="addressBookRef" />
	</WithFixedPageContainer>
</template>

<script setup lang="ts">
import { ElMessageBox } from 'element-plus';
import { ref, reactive, computed } from 'vue';
import AddCustomer from './components/addCustomer.vue';
const addCustomerRef = ref();
import { useDict } from '/@/hooks/dict';
const dicts = useDict(['xzqh']);
import AddressBook from './components/addressBook.vue';
const addressBookRef = ref();
// 搜索表单配置
const formList = computed((): BasicTableNameSpace.FormItemType[] => [
	{
		key: 'region',
		type: 'select',
		label: '所属辖区:',
		placeholder: '请选择辖区',
		clearable: true,
		multiple: true,
		options: dicts.xzqh.value,
	},
	{
		key: 'customerType',
		type: 'select',
		label: '客户类型:',
		placeholder: '请选择客户类型',
		clearable: true,
		options: [
			{ label: '全部', value: '' },
			{ label: '个人客户', value: '个人客户' },
			{ label: '企业客户', value: '企业客户' },
		],
	},
	{
		key: 'keyword',
		type: 'input-text',
		label: '关键字:',
		placeholder: '客户名称/联系电话',
		clearable: true,
	},
]);

// 表格列配置
const tableColumns = {
	index: true,
	menuWidth: 180,
	column: [
		{ label: '客户名称', prop: 'name' },
		{ label: '客户编号', prop: 'code' },
		{ label: '所属辖区', prop: 'region' },
		{ label: '客户类型', prop: 'customerType' },
		{ label: '联系人', prop: 'contact' },
		{ label: '联系电话', prop: 'phone' },
		{ label: '累计订单数', prop: 'orderCount' },
		{ label: '状态', prop: 'status' },
	],
};

const page = reactive({
	total: 0,
	currentPage: 1,
	pageSize: 30,
});

const tableData = ref([
	{
		id: 1,
		name: 'XXXXXX',
		code: 'KH00001',
		region: '都江堰',
		customerType: '个人客户',
		contact: 'XXX',
		phone: '135XXXXXXXX',
		orderCount: 30,
		status: '正常',
		addressList: [
			{
				id: '1',
				title: '雪门寺砂场',
				region: '四川省 成都市 青羊区 蔡桥街道',
				detail: 'XXX路XXX号  XXXXXXXX小区X栋X单元XX号',
				contact: '司马杰龙',
				phone: '13512341234',
			},
			{
				id: '2',
				title: '北川天安',
				region: '四川省 成都市 青羊区 蔡桥街道',
				detail: 'XXX路XXX号  XXXXXXXX小区X栋X单元XX号',
				contact: '司马杰龙',
				phone: '13512341234',
			},
			{
				id: '3',
				title: '成都高新',
				region: '四川省 成都市 高新区 天府大道',
				detail: '天府大道中段888号 创新中心A座101',
				contact: '李四',
				phone: '13987654321',
			},
		],
		defaultAddressId: '1',
	},
	{
		id: 2,
		name: '',
		code: '',
		region: '',
		customerType: '企业客户',
		contact: '',
		phone: '',
		orderCount: 0,
		status: '停用',
		addressList: [
			{
				id: '4',
				title: '天府软件园',
				region: '四川省 成都市 高新区 天府大道',
				detail: '天府大道中段999号 软件园B区201',
				contact: '王五',
				phone: '13888888888',
			},
		],
		defaultAddressId: '4',
	},
]);
const loading = ref(false);

function handleSearch(data: any) {
	// TODO: 查询逻辑
	console.log(data);
}
function handleAddNew() {
	// 自动生成客户编号，KH+6位数字（示例：KH000001）
	const maxId = tableData.value.reduce(
		(max, item) => Math.max(max, parseInt(item.code?.replace('KH', '')) || 0),
		0,
	);
	const nextCode = `KH${String(maxId + 1).padStart(6, '0')}`;
	addCustomerRef.value.open({ code: nextCode });
}
function handleEdit(row: any) {
	// TODO: 编辑客户逻辑
	console.log(row);
}
function handleDisable(row: any) {
	ElMessageBox.confirm(
		`确认要停用客户"${row.name}"吗？停用后该客户将不能再下订单。`,
		'提示',
		{
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		},
	).then(() => {
		// TODO: 停用客户逻辑
		console.log(row);
	});
}
function handleEnable(row: any) {
	ElMessageBox.confirm(
		`确认要启用客户"${row.name}"吗？启用后该客户将可以正常下订单。`,
		'提示',
		{
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		},
	).then(() => {
		// TODO: 启用客户逻辑
		console.log(row);
	});
}
function handleAddressBook(row: any) {
	// 假设row.addressList为客户地址列表，row.status为客户状态
	addressBookRef.value.open({
		list: row.addressList || [],
		readonly: row.status !== '正常',
		defaultId: row.defaultAddressId || '',
	});
}
function handleOrderCount(row: any) {
	// TODO: 累计订单数点击逻辑 跳转订单列表
	console.log(row);
}
</script>

<style lang="scss" scoped>
.el-input {
	--el-input-width: auto;
}
</style>
